<template>
  <div class="Index">
    <el-container>
      <!-- 头部布局 -->
      <el-header>
        <img src="/static/logo.png">
        <span>问卷系统 - </span>
          <img :src="url" alt="" class="iavatar">
        {{hformUsers?hformUsers.username:''}}
        <el-button type="text" @click="logout">注销</el-button>
      </el-header>
      <el-container>
        <!-- 左侧布局 -->
        <el-aside width="200px">
          <!-- 基本样式 -->
          <el-menu :router="true" default-active="1">
            <template v-for="menu in menus" >
              <el-menu-item :index="menu.router" :key="'m_'+menu.id" v-if="!menu.children[0]">
                <i :class="menu.icon"></i>
                <span slot="title">{{menu.menu_name}}</span>
              </el-menu-item>

               <!-- 下拉样式 -->
              <el-submenu v-else :index="menu.router" :key="'m_'+menu.id" >
                <template slot="title">
                  <i :class="menu.icon"></i>
                  {{menu.menu_name}}
                </template>
                <el-menu-item v-for=" submenu in menu.children" :key="'s_'+submenu.id" :index="menu.router">
                  <i :class="submenu.icon"></i>
                  {{submenu.menu_name}}
                </el-menu-item>
              </el-submenu>
            </template>
            
           
          </el-menu>
          <!-- {{menus}} -->
          


        </el-aside>
        <!-- 右侧布局 -->
        <el-main>
          <router-view></router-view>
        </el-main>
      </el-container>
    </el-container>
  </div>
            
</template>

<script>
export default {
  data() {
    let baseUrl = this.axios.defaults.baseURL
    return {
      menus:[],
      hformUsers: {},
      baseUrl,
      url:baseUrl+this.store("loggedInfo").avatar,
    };
  },
  beforeRouteEnter(to,from,next){
    next((vm)=>{
      if(!vm.store('logged')){
        vm.$router.push('/login');
      }
    })
  },
  created(){
     this.hformUsers = this.store("loggedInfo")
     //监听菜单更新
    this.$root.$on('freshMnues',()=>{
      console.log('hello')
      this.getMenus();
    });
    //监听用户名更新
    this.$root.$on('storeUsername',()=>{
      location.reload()
    });
    //监听用户头像更新
    this.$root.$on('upImg',()=>{
      this.url = this.baseUrl+this.store("loggedInfo").avatar;
      let loggedInfo = this.store("loggedInfo");
      loggedInfo.avatar = this.store("loggedInfo").avatar;
      this.store("loggedInfo", loggedInfo);
    });
    this.getMenus();
  },
  methods:{
    getMenus(){
      this.axios.get('/menus').then((ret)=>{
        this.menus=ret.data;
      }).catch(()=>{
        this.$message.error('菜单获取失败')
      })
    },
    logout(){
      this.axios.get('/users/logout').then(()=>{
        this.store(null);
        this.$router.push('/login');
        this.$message.success('注销成功');
      }).catch(()=>{
        this.$message.error('注销失败');
      })
     
    }
  }
};
</script>
<style>
.iavatar{
  width:20px;
  height: 20px;
}
</style>

